#!/bin/sh /etc/rc.common
# maz-1 <ohmygod19993@gmail.com>

START=99
STOP=99
SERVICE_DAEMONIZE=1

#ATTACH="/usr/sbin/screen -dm -t rtorrent"
#ATTACH="/usr/bin/dtach -n /var/run/rtorrent/rtorrent.socket -r winch"
PROG=/usr/bin/rtorrent

#trap "get SIGINT" INT

append_params() {
	local p; local v; local s="$1"; shift
	for p in $*; do
		config_get v "$s" "$p"
		[ -n "$v" ] && (
			#p=$(echo "$p" | sed -e 's|_|-|g');
			echo "$p = $v" >> $config_file
			)
	done
}

append_params_with_dot() {
	local p; local v; local s="$1"; shift
	for p in $*; do
		config_get v "$s" "$p"
		[ -n "$v" ] && (
			p=$(echo "$p" | sed -e 's|__|.|g');
			echo "$p = $v" >> $config_file
			)
	done
}

append_encrypt_param() {
	local p; local v; local s="$1"; shift
	tmpfile="/tmp/rtorrent_enc_tmp_$PID"
	rm -f "$tmpfile"
	for p in $*; do
		config_get v "$s" "$p"
		[ -n "$v" ] && (
			#p=$(echo "$p" | sed -e 's|_|-|g');
			printf "$p" | sed 's/encryption_/ /g' >> $tmpfile
			)
	done
	if [[ -s $tmpfile ]] ; then
		echo "encryption = $(cat $tmpfile | sed -e 's/^ //g' -e 's/ /,/g')" >> $config_file
	else
		echo "encryption = none" >> $config_file
	fi
	rm -f "$tmpfile"
}

section_enabled() {
	local result
	config_get_bool result "$1" 'enabled' 0
	[ $result -eq 1 ]
}

option_enabled() {
	local result
	config_get_bool result "$1" "$2" 0
	[ $result -eq 1 ]
}

set_owner() {
	case $(echo "$1"|grep -oE "^/[^/]+") in
	"/var"|"/tmp"|"/mnt"|"root")
		#cur_user=$(ls -w50 -ld "$1"|awk '{print $3}')
		#cur_group=$(ls -w50 -ld "$1"|awk '{print $4}')
		#[[ $cur_user == $2 ]] || ( chown -R $2 "$1" )
		#[[ $cur_group == $3 ]] || ( chgrp -R $3 "$1" )
		chmod g+s "$1"
		chown $3:$2 "$1"
	;;
	*)
		false
	;;
	esac
}

start_instance() {
	local s="$1"
	local user config_dir config_file

	section_enabled "$s" || return 1
	
	config_get nice "$s" nice '-19'
	config_get ionice_flags "$s" ionice_flags '-c3'
	
	config_get directory "$s" 'directory'
	config_get session "$s" 'session'
	config_get user "$s" 'user' 'root'
	#user=root
	group=$(id -Gn $user)
	#config_dir=$(cat /etc/passwd | grep -E "^${user}:" | awk -F: '{print $6}')
	config_dir="/var/run/rtorrent"
	#[[ -n $config_dir ]] || config_dir="/var"
	
	config_file="$config_dir/.rtorrent.rc"
	
	[ -d "$config_dir" ] || {
		mkdir -m 0755 -p "$config_dir"	# create config dir
		touch "$config_file"
	}
	set_owner "$config_dir" $user $group
	
	[ -d "$directory" ] || {
		mkdir -m 0755 -p "$directory"	# create download dir
	}
	set_owner "$directory" $user $group

	[ -d "$session" ] || {
		mkdir -m 0755 -p "$session"	# create session dir
	}
	set_owner "$session" $user $group
	
	printf "" > "$config_file"
	
	#config_get xmlrpc_host "$s" 'xmlrpc_host' '0.0.0.0'
	xmlrpc_host="127.0.0.1"
	config_get xmlrpc_port "$s" 'xmlrpc_port' '5001'
	option_enabled "$s" 'xmlrpc_enable' && echo "scgi_port=$xmlrpc_host:$xmlrpc_port" >> "$config_file"
	
	append_params "$s" directory session encoding_list check_hash \
		download_rate upload_rate min_peers max_peers min_peers_seed max_peers_seed \
		max_uploads port_range port_random dht
		
	
	append_params_with_dot "$s" system__file__allocate__set network__send_buffer__size \
		network__receive_buffer__size protocol__pex__set trackers__use_udp__set \
		system__file__split_size__set system__file__split_suffix__set pieces__memory__max__set
	
	append_encrypt_param "$s" encryption_allow_incoming encryption_try_outgoing \
		encryption_require encryption_require_RC4 encryption_enable_retry \
		encryption_prefer_plaintext
	
	config_get feed_interval "$s" 'feed_interval' '300'
	option_enabled "$s" 'enable_rss' && \
		echo -e "\n# Update RSS\nschedule = rss_downloader,${feed_interval},${feed_interval},\"execute=/usr/share/rtorrent/rss_downloader.lua\"" \
		>> "$config_file"
	
	echo -e "\n# Wrtie PID\nexecute = {/bin/sh,-c,\"echo \$PPID > ${config_dir}/rtorrent.pid\"}" >> "$config_file"
	rm -f "${config_dir}/rtorrent.pid"
	
	echo -e "\n# Options from /etc/rtorrent/rtorrent.rc.extra\n"  >> "$config_file"
	
	cat /etc/rtorrent/rtorrent.rc.extra >> "$config_file"
	
	#echo "$config_file"
	#cat "$config_file"
	which ionice > /dev/null && ionice_cmd="ionice $ionice_flags" || ionice_cmd=""
	ATTACH="/usr/bin/dtach -n $config_dir/rtorrent.socket -r winch"
	SERVICE_UID="$user" HOME="$config_dir" \
	service_start $ATTACH nice $nice $ionice_cmd $PROG # start service
}

start() {
	logger -t RTORRENT 'Starting rtorrent service'
	config_load 'rtorrent'
	
	config_foreach start_instance 'rtorrent'
	service_start /usr/bin/lua /usr/share/rtorrent/bind.lua
	return 0
}

stop() {
	kill -2 $(pidof rtorrent|sed "s:$$::g") >/dev/null 2>&1
	service_stop /usr/bin/lua /usr/share/rtorrent/bind.lua
	#rm -f /tmp/luci-indexcache
}

restart() {
	stop
	sleep 3
	start
}

boot() {
	sleep 10
	start
}
